# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg2.utils import swagger_auto_schema
from rest_framework import viewsets, status
from rest_framework import filters
from api.myfilter import BlogPostFilter, UserFilter
from api.serializers import *
from blog.models import BlogCategory, BlogPost, Site, Social, Focus, Friend, Tag
from django.contrib.auth.models import User
from api.mypage import MyPage
from common.custommodelviewset import CustomModelViewSet
from common.customresponse import CustomResponse


class UserViewset(CustomModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserModelSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_class = UserFilter


class BlogCategoryViewset(CustomModelViewSet):
    queryset = BlogCategory.objects.all()
    serializer_class = BlogCategoryModelSerializer

    def destroy(self, request, *args, **kwargs):
        if BlogPost.objects.filter(category=kwargs['pk']).exists():
            return CustomResponse(code=400, msg="该分类下有文章，无法删除!", status=status.HTTP_200_OK)
        try:
            super().destroy(request, *args, **kwargs)
            return CustomResponse(code=200, msg="删除成功", status=status.HTTP_200_OK)
        except Exception as e:
            return CustomResponse(code=400, msg="删除失败," + str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class BlogsView(CustomModelViewSet):
    queryset = BlogPost.objects.all().order_by('-isTop', '-pubTime', '-update_time')
    serializer_class = BlogPostModelSerializer
    pagination_class = MyPage
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filterset_class = BlogPostFilter
    # 搜索
    search_fields = ('title',)
    # 排序
    ordering_fields = ('isTop', 'update_time')

    # 自定义获取详情接口
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.viewsCount += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return CustomResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)


class SiteView(CustomModelViewSet):
    queryset = Site.objects.all()
    serializer_class = SiteModelSerializer


class SocialView(CustomModelViewSet):
    queryset = Social.objects.all()
    serializer_class = SocialModelSerializer


class FocusView(CustomModelViewSet):
    queryset = Focus.objects.all()
    serializer_class = FocusModelSerializer


class FriendView(CustomModelViewSet):
    queryset = Friend.objects.all()
    serializer_class = FriendModelSerializer


class TagView(CustomModelViewSet):
    queryset = Tag.objects.all().order_by('-id')
    serializer_class = TagModelSerializer

    # 分页
    pagination_class = MyPage

    # 根据参数确定是否要分页
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        # 是否启用分页
        should_paginate = request.query_params.get('no_pagination', 'false').lower() != 'true'

        if should_paginate:
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.paginator.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return CustomResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)


class MenuView(CustomModelViewSet):
    queryset = Menu.objects.all()
    serializer_class = MenuModelSerializer


class RoleView(CustomModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleModelSerializer






